package action;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.print.attribute.standard.DateTimeAtCompleted;
import javax.servlet.http.HttpServletRequest;

import model.CartModel;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

import pojo.Cart;

import com.opensymphony.xwork2.ActionSupport;

import dao.CartDAO;
import dao.UserDAO;

public class CartAction extends ActionSupport implements RequestAware, SessionAware {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1742891107833112229L;
	private Map<String, Object> request;
    private Map<String, Object> session;
    
    @Autowired
	private UserDAO UserDAO;
    
    @Autowired
	private CartDAO CartDAO;
    
	public void setSession(Map<String, Object> arg0) {
		this.session = arg0;
	}

	public void setRequest(Map<String, Object> arg0) {
		this.request = arg0;
	}
	
	private int remove = -1;
	public int getRemove() {
		return remove;
	}
	public void setRemove(int remove) {
		this.remove = remove;
	}
	
	private String action = "";
	public String getAction() {
		return action;
	}
	public void setAction(String action) {
		this.action = action;
	}

	public String execute() {

		List<Integer> listnum = new ArrayList<Integer>();
		for (int i = 1; i <= 10; i++)
			listnum.add(i);
		request.put("listnum", listnum);
		
		CartModel cartModel = (CartModel)session.get("cart");
		
		HttpServletRequest _request = ServletActionContext.getRequest();
		if (_request.getParameter("action") != null && _request.getParameter("action").equals("Update") && cartModel != null)
		{
			String[] s = _request.getParameterValues("quantity");
			
			cartModel.price = BigDecimal.ZERO;
			cartModel.totalQuantity = 0;
			
			for (int i = 0; i < cartModel.listProduct.size(); i++) {
                int num = Integer.parseInt(s[i]);
                cartModel.listProduct.get(i).quantity = num;
                cartModel.listProduct.get(i).price = cartModel.listProduct.get(i).productcart.getPrice().multiply(BigDecimal.valueOf((long)cartModel.listProduct.get(i).quantity));
                
                cartModel.price = cartModel.price.add(cartModel.listProduct.get(i).price);
                cartModel.totalQuantity += cartModel.listProduct.get(i).quantity;
            }
		}
		else if ( action != "" && action.equals("Checkout") )
		{
			try{
				if ( ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername() == null )
				{
					return "loginpage";
				}
				else
				{
					if (cartModel == null)
					{
						request.put("error", "You cart is empty !!!");
						return SUCCESS;
					}
					Cart cartCheckout = new Cart();
					cartCheckout.setTotalPrice(cartModel.totalPrice);
					cartCheckout.setUserProfile( UserDAO.getUserProfile(((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()) );
					cartCheckout.setStatus("Pending");
					cartCheckout.setDate(new Date());
					
					if ( CartDAO.addCart(cartCheckout, cartModel.listProduct) )
					{
						session.remove("cart");
						request.put("success", "Check out success.");
						return SUCCESS;
					}
					else
					{
						request.put("error", "Can not check out your cart !!!");
						return SUCCESS;
					}
				}
			} catch (Exception ex)
			{
				return "loginpage";
			}
		}
		
		if (remove >= 0 && remove < cartModel.listProduct.size())
		{
			cartModel.price = cartModel.price.subtract(cartModel.listProduct.get(remove).productcart.getPrice().multiply(BigDecimal.valueOf((long)cartModel.listProduct.get(remove).quantity)));
			cartModel.totalQuantity -= cartModel.listProduct.get(remove).quantity;
			cartModel.listProduct.remove(remove);
		}
		
		if (cartModel != null)
		{
			cartModel.ship = cartModel.price.multiply(BigDecimal.valueOf(0.1f)).setScale(2, BigDecimal.ROUND_CEILING);
			cartModel.taxes = cartModel.price.multiply(BigDecimal.valueOf(0.1f)).setScale(2, BigDecimal.ROUND_CEILING);
			cartModel.totalPrice = cartModel.price.add(cartModel.taxes).add(cartModel.ship).setScale(2, BigDecimal.ROUND_CEILING);
		}
		
        return SUCCESS;
    }
}
